from ninja import Router

from apps.schemas import R
from apps.user_applets.shop_cart.schemas import ShopCartSerializer
from models.models import ShopCart
from utils.auth import AppletAuthBearer

from utils.decorators import handle_exception

shop_cart_router = Router(tags=["购物车"], auth=AppletAuthBearer())


@shop_cart_router.get("/shop_carts", summary="获取购物车列表")
@handle_exception("获取购物车列表失败")
def get_shop_carts(request):
    carts = ShopCart.objects.filter(user=request.user)
    return R.ok(ShopCartSerializer(carts, many=True).data)


@shop_cart_router.delete("/shop_cart/{shop_cart_id}", summary="删除购物车")
@handle_exception("删除购物车失败")
def delete_shop_cart(request, shop_cart_id: int):
    if not ShopCart.objects.filter(id=shop_cart_id).exists():
        return R.fail("购物车不存在")
    ShopCart.objects.get(id=shop_cart_id).delete()
    return R.ok(msg="删除成功")
